<template>
	<view class="login-container">
		<!-- 提示登录的图标 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- 登录按钮 -->
		<button type="primary" class="btn-login" @click="getUserProfile">一键登录</button>
		<!-- 登录提示 -->
		<view class="tips-text">登录后尽享更多功能</view>
	</view>
</template>

<script>
import {
	mapState,
	mapMutations
} from "vuex"
export default {
	data() {
		return {

		};
	},
	methods: {
		...mapMutations('user', ['updateUserInfo', 'updateUserToken', 'updateRedirectInfo']),
		async getUserProfile() {
			if (uni.getUserProfile) {
				const [err, data] = await uni.getUserProfile({
					desc: '用于完善资料'
				})
				// 判断是否获取用户信息成功
				if (err && err.errMsg === "getUserProfile:fail auth deny") return uni.$showMsg('您取消了登录授权！')
				console.log('用户信息:', data)
				this.updateUserInfo(data.userInfo)

				this.getToken(data.userInfo)
			}
		},
		// 登录获取token
		async getToken(userInfo) {
			const [err, data] = await uni.login().catch(err => err)
			if (err || data.errMsg !== 'login:ok')
				return uni.$showMsg('登录失败')
			const query = {
				code: data.code,
				nickName: userInfo.nickName,
				avatarUrl: userInfo.avatarUrl
			}
			try {
				const {
					data: ret
				} = await uni.$http.post('/user/doLogin', query)
				console.log('登录信息', ret);
				if (ret.code == 200) {
					this.updateUserInfo({
						userId: ret.userId
					})
					this.updateUserToken(ret.token)
				}

				// 返回到前往的页面
				this.navigateBack()
			} catch (e) {
				//TODO handle the exception
				console.log('登录失败', e);
			}
		},

		// 回跳到指定页面
		navigateBack() {
			if (this.redirectInfo) {
				uni.redirectTo({
					url: this.redirectInfo,
					// 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
					complete: () => {
						this.updateRedirectInfo(null)
					}
				})
			}
		}
	},

	computed: {
		...mapState('user', ['redirectInfo'])
	},

}
</script>

<style lang="less" scoped>
.login-container {
	// 登录盒子的样式
	height: 750rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #f8f8f8;
	position: relative;
	overflow: hidden;

	// 绘制登录盒子底部的半椭圆造型
	&::after {
		content: ' ';
		display: block;
		position: absolute;
		width: 100%;
		height: 40px;
		left: 0;
		bottom: 0;
		background-color: white;
		border-radius: 100%;
		transform: translateY(50%);
	}

	// 登录按钮的样式
	.btn-login {
		width: 90%;
		border-radius: 100px;
		margin: 25px 0;
		font-size: 25px;
		background-color: #c00000;
	}

	// 按钮下方提示消息的样式
	.tips-text {
		font-size: 18px;
		color: gray;
	}
}
</style>
